package com.songlanyun.modules.notice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.modules.category.service.SystemProductCategoryService;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.modules.goods.entity.GoodsAuthShop;
import com.songlanyun.modules.goods.entity.GoodsSku;
import com.songlanyun.modules.goods.service.GoodsAuthShopService;
import com.songlanyun.modules.goods.service.GoodsContentService;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.goods.service.GoodsSkuService;
import com.songlanyun.modules.goods.service.impl.GoodsServiceImpl;
import com.songlanyun.modules.jst.dao.jstDao;
import com.songlanyun.modules.jst.entiy.JstRecord;
import com.songlanyun.modules.logisticsconfig.entity.LogisticsConfig;
import com.songlanyun.modules.notice.service.GoodsNoticeService;
import com.songlanyun.modules.order.entity.ChildOrder;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.rabbitmq.mq.producer.SendOrderOrRightsOrderMsgService;
import com.songlanyun.modules.saleconfig.entity.SaleConfig;
import com.songlanyun.modules.saleconfig.service.SaleConfigService;
import com.songlanyun.modules.ship.entity.OrderPackage;
import com.songlanyun.modules.ship.model.dto.ShipItemDTO;
import com.songlanyun.modules.ship.service.OrderPackageService;
import com.songlanyun.modules.shop.dao.ShopDao;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.skus.entity.ProductSkusEntity;
import com.songlanyun.modules.skus.service.ProductSkusService;
import lombok.val;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.songlanyun.modules.ship.model.dto.ExpressShipDTO;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("GoodsNoticeService")
public class GoodsNoticeServiceImpl  implements GoodsNoticeService {

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ChildOrderService childOrderService;
    @Autowired
    private OrderPackageService orderPackageService;
    @Autowired
    private SaleConfigService saleConfigService;
    @Autowired
    private SendOrderOrRightsOrderMsgService sendOrderOrRightsOrderMsgService;
    @Autowired
    private GoodsAuthShopService goodsAuthShopService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private SystemProductCategoryService systemProductCategoryService;

    @Autowired
    private GoodsContentService goodsContentService;

    @Autowired
    private ProductSingleGoodsService productSingleGoodsService;

    @Autowired
    private ProductSkusService productSkusService;

    @Autowired
    private GoodsServiceImpl goodsServiceImpl;

    @Autowired
    private jstDao jstDao;



//    /**
//     * 商品新增
//     */
//    public void add(String goods_spu) {
//        JSONObject req = new JSONObject();
//        req.put("goods_spu",goods_spu);
//        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_INFO.getUrl());
//
//        //做非空判断
//        Goods good = goodsService.getByGoodsSpu(goods_spu);
//        if (good != null){
//            throw new RRException("商品已存在");
//        }
//        //获取商品规格
//        JSONObject req1 = new JSONObject();
//        req1.put("goods_spu",goods_spu);
//        JSONObject json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
//        JSONArray data3 = json.getJSONArray("data");
//        JSONObject jsonObject1 = data3.getJSONObject(0);
//        JSONArray sku_list = jsonObject1.getJSONArray("sku_list");
//        //商品如果没有规格 不添加该商品
//        if(sku_list.size() == 0){
//            throw new RRException("商品规格为空");
//        }
//
//
//        // 实例化商品详情List
//        List<JSONObject> goodsInfoList = new ArrayList<>();
//        //候鸟商品集合
//        ArrayList<Goods> houNiaoGoodsList = new ArrayList<>();
//        // 追加到商品详情list
//        goodsInfoList.add(js);
//
//        // 存商品表
//        Goods goods = goodsServiceImpl.goodsAdd(js);
//        houNiaoGoodsList.add(goods);
//
//        //TODO:商品整体保存  做重复校验
//        goodsService.saveBatch(houNiaoGoodsList);
//        // 其他表存储
//        goodsService.goodsDetailsAndInventoryPreservation(houNiaoGoodsList, goodsInfoList);
//
//    }

    @Override
    public void add(String goods_spu) {

    }

    /**
     * 商品更新
     * @param goods_spu
     */
    @Override
    public void update(String goods_spu) {
        Goods g = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goods_spu));
        Long goodsId = g.getId();
        Goods good = goodsService.getById(goodsId, true);
    }

    /**
     * 上架通知
     * @param goods_spu
     */
    @Override
    public void shelve(String goods_spu) {
        Goods g = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goods_spu));
        Long goodsId = g.getId();
        GoodsAuthShop goodsAuthShop = goodsAuthShopService.getOne(
                new LambdaQueryWrapper<GoodsAuthShop>()
                        .eq(GoodsAuthShop::getGoodsId, goodsId));
        goodsAuthShop.setAdded(true);
        goodsAuthShop.setAddedStatusTime(new Date());
        goodsAuthShop.setUpdateTime(new Date());
        goodsAuthShopService.updateById(goodsAuthShop);
    }

    /**
     * 下架通知
     * @param goods_spu
     */
    @Override
    public void unshelve(String goods_spu) {
        Goods g = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goods_spu));
        Long goodsId = g.getId();
        GoodsAuthShop goodsAuthShop = goodsAuthShopService.getOne(
                new LambdaQueryWrapper<GoodsAuthShop>()
                        .eq(GoodsAuthShop::getGoodsId, goodsId));
        goodsAuthShop.setAdded(false);
        goodsAuthShop.setUpdateTime(new Date());
        goodsAuthShopService.updateById(goodsAuthShop);
    }

    /**
     * 商品价格库存更新通知
     * @param goods_spu
     */
    @Override
    public void price(String goods_spu) {
        Goods g = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goods_spu));
        Long goodsId = g.getId();
        Goods good = goodsService.getById(goodsId, true);
    }

    /**
     * 商品库存更新通知
     * @param goods_spu
     */
    @Override
    public void stock(String goods_spu) {
        Goods g = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goods_spu));
        Long goodsId = g.getId();
        Goods good = goodsService.getById(goodsId, true);
    }


    /**
     * 更新订单发货信息
     */
    @Override
    public void orderSend(JSONObject param){
        String orderNo = param.getString("order_no");
        //子订单数据
        ChildOrder childOrder = childOrderService.getOne(new LambdaQueryWrapper<ChildOrder>().eq(ChildOrder::getThirdOrderNo, orderNo));
        //根据三方订单号查询是否有过包裹信息
        if(childOrder == null){
            throw new RRException("订单不存在");
        }
        if(!childOrder.getTransactionStatus().equals(OrderConstant.TransactionStatus.WAIT_SHIP)){
            throw new RRException("订单异常");
        }
        ExpressShipDTO expDto = new ExpressShipDTO();
        //-------------
        ShipItemDTO shipDto = new ShipItemDTO();
        JSONArray goods = param.getJSONArray("order_goods");
        shipDto.setChildOrderId(childOrder.getId());
        shipDto.setShipNum(goods.getJSONObject(0).getInteger("goods_num"));
        shipDto.setOrderId(childOrder.getOrderId());
        //------------
        JSONArray express = param.getJSONArray("express");
        expDto.setExpressCode(express.getJSONObject(0).getString("express_code"));
        expDto.setExpressName(express.getJSONObject(0).getString("express_name"));
        expDto.setLogisticCode(express.getJSONObject(0).getString("express_no"));
        expDto.setOrderId(childOrder.getOrderId());
        //-----------
        ArrayList<ShipItemDTO> shipItemDTOS = new ArrayList<>();
        shipItemDTOS.add(shipDto);
        expDto.setShipItems(shipItemDTOS);
        OrderPackage orderPackage = orderPackageService.partExpressShip(childOrder.getShopId(),expDto);
        sendOrderOrRightsOrderMsgService.expressShipSuccessSendMsg(orderPackage);


    }

    /**
     * 订单状态更新通知
     */
    @Override
    public void orderStatus(JSONObject param){
        String orderNo = param.getString("order_no");
        Integer orderStatus = param.getInteger("order_status");
        if(orderStatus != 2){
            throw new RRException("无效订单状态");
        }
        ChildOrder childOrder = childOrderService.getOne(new LambdaQueryWrapper<ChildOrder>().eq(ChildOrder::getThirdOrderNo, orderNo));
        if(!childOrder.getTransactionStatus().equals(OrderConstant.TransactionStatus.WAIT_RECEIPT)){
//            throw new RRException("订单已完成");
            throw new RRException("订单状态异常");
        }
//        System.out.println(OrderConstant.TransactionStatus.WAIT_RECEIPT.getCode());  //返回状态码
//        OrderConstant.TransactionStatus byCode = OrderConstant.TransactionStatus.getByCode(orderStatus);
//        if(childOrder.getTransactionStatus().equals(OrderConstant.TransactionStatus.COMPLETE)){
//            throw new RRException("订单已完成");
//        }
        ExpressShipDTO expressShipDTO = new ExpressShipDTO();
        expressShipDTO.setOrderId(childOrder.getOrderId());
        Order order = orderPackageService.receipt(childOrder.getUserId(),expressShipDTO);
        sendOrderOrRightsOrderMsgService.receiptSuccessSendMsg(order);
    }


    @Override
    public JSONObject orderJstSend(JSONObject param) {

        System.out.println(param.get("o_id").toString());

        QueryWrapper<JstRecord> jstQueryWrapper = new QueryWrapper<>();
        //根据oid查找订单id
        jstQueryWrapper.eq("o_id",param.get("o_id"));
        JstRecord record = jstDao.selectOne(jstQueryWrapper);

        //订单id
        Long orderId = record.getOrderId();

        ChildOrder childOrder = childOrderService.getOne(new LambdaQueryWrapper<ChildOrder>().eq(ChildOrder::getOrderId, orderId));

        ExpressShipDTO expDto = new ExpressShipDTO();
        //-------------
        ShipItemDTO shipDto = new ShipItemDTO();
        shipDto.setChildOrderId(childOrder.getId());
        shipDto.setShipNum(childOrder.getNumber());
        shipDto.setOrderId(orderId);
        //------------
        expDto.setExpressCode(param.get("lc_id").toString());
        expDto.setExpressName(param.get("logistics_company").toString());
        expDto.setLogisticCode(param.get("l_id").toString());
        expDto.setOrderId(orderId);
        //-----------
        ArrayList<ShipItemDTO> shipItemDTOS = new ArrayList<>();
        shipItemDTOS.add(shipDto);
        expDto.setShipItems(shipItemDTOS);
        OrderPackage orderPackage = orderPackageService.partExpressShip(childOrder.getShopId(),expDto);
        sendOrderOrRightsOrderMsgService.expressShipSuccessSendMsg(orderPackage);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "0");
        jsonObject.put("msg", "成功");
        return jsonObject;
    }


}
